package com.acxy.ants.core.proxy;

import com.acxy.ants.core.annotation.Cache;
import com.acxy.ants.core.plugin.ehcache.CacheKit;
import com.acxy.ants.common.kit.StrKit;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-06-07
 */
public class CacheInvcation {


    private Cache methodCache;

    private String cacheKey;

    public CacheInvcation(Object target, Method method, Object[] args){
        methodCache = method.getAnnotation(Cache.class);
        cacheKey = target.getClass().getSimpleName()+"."+method.getName();
        if(args!=null && args.length!=0) {
            StringBuffer sb = new StringBuffer("[0");
            for(Object arg: args) {
                if(args.getClass().isPrimitive()) sb.append("," +arg);
            }
            sb.append("]");
            cacheKey = cacheKey.concat(sb.toString()); //"+ JSON.toJSONString(args) +"
        }
    }

    public Object handler(){
        if (methodCache != null) {
            String name = methodCache.value();
            if(CacheKit.cacheManager == null) throw new RuntimeException(methodCache.type() + " 没有配置相应的缓存插件!");
            System.out.println(name+"|"+ cacheKey);
            Object data = CacheKit.get(name, cacheKey);
            if(data != null) return data;
        }
        return null;
    }

    public void cacheResult(Object result){
        if (methodCache != null) {
            String name = methodCache.value();
            CacheKit.put(name, cacheKey, result);
        }
    }
}
